<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改买房信息')" />
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-apartment-edit" th:object="${apartment}">
        <div class="form-group">
            <input name="id" th:field="*{id}" class="form-control" type="hidden" required>

        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">标题</label>
            <div class="col-sm-8">
                <input name="title" th:field="*{title}" class="form-control" type="text" required>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label is-required">图片上传</label>
            <div class="col-sm-8">
                <label class="control-label">选择文件</label>
                <input class="projectfile" id="attach" multiple name="file"  type="file"/>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">价格(万)：</label>
            <div class="col-sm-8">
                <input name="price" th:field="*{price}" class="form-control" type="text" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">房产类型</label>
            <div class="col-sm-8">
                <input name="typehouseArea" th:field="*{typehouseArea}" class="form-control" type="text" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">优点标签</label>
            <div class="col-sm-8">
                <select id="advantage" class="form-control select2-multiple" multiple>
                    <option th:each="advantage:${advantages}" th:value="${advantage.advantageId}" th:text="${advantage.advantageName}" th:selected="${advantage.flag}" th:disabled="${advantage.status == '1'}">

                    </option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">是否需要显示</label>
            <div class="col-sm-8" style="margin-top: 5px">
                <!--                    <input name="ifNeedShow" th:field="*{ifNeedShow}" class="form-control" type="text" required>-->
                <input type="radio" name="ifNeedShow" value="1" th:attr="checked=*{ifNeedShow}" />是&nbsp;&nbsp;&nbsp;&nbsp;
                <input type="radio" name="ifNeedShow" value="0" th:attr="checked=!*{ifNeedShow}" />否



            </div>
    </form>
</div>


<th:block th:include="include :: footer" />
<th:block th:include="include :: select2-js" />
<th:block th:include="include :: select2-css" />
<th:block th:include="include :: bootstrap-fileinput-css"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>


<script th:inline="javascript">

    var prefix = ctx + "system/apartment";
    $("#form-apartment-edit").validate({
        focusCleanup: true
    });

    function submitHandler() {
        if ($.validate.form()) {
            var data=$('#form-apartment-edit').serializeArray();

            var advantage = $.form.selectSelects("advantage");

            data.push({"name": "advantages", "value": advantage});

            $('.projectfile').attr("disabled","")

            mySave(prefix + "/edit", data);

        }
    }

    //改造ruyisave方法
    function mySave(url, data, callback) {
        var config = {
            url: url,
            type: "post",
            dataType: "json",
            data: data,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍候...");
                $.modal.disable();
            },
            success: function(result) {
                if (typeof callback == "function") {
                    callback(result);
                }
                //更新插入的id,然后自动上传图片
                console.log(result)
                //得到上传id
                uploadId=result.id;
                //模拟点击上传按钮
                $("[class='kv-file-upload btn btn-sm btn-kv btn-default btn-outline-secondary']").trigger("click");
                $.operate.successCallback(result);

            }
        };
        $.ajax(config)
    }
    $( function() {
        //标签原始数据
        var advantageRawRes;
        $.ajax({
            type:"post",
            url:"/system/apartment/getAdvantageApartment?apartmentId="+ $('input[name="id"]').val(),
            success:function (res) {
                res="["+res+"]";
                var tag=JSON.parse(res);//把json字符串变成数组
                $('#advantage').val(tag).trigger('change')
                $('#advantage').select2({
                    placeholder: "请选择优点标签",
                    allowClear: true
                });
            }

        });





    })





    //买房表的首页图片地址
    var apartmentImageAddress="";
    //文件名加后缀
    var apartmentImageAddressOnlyNameAndSuffix="";
    //初始化的标签,如果有就添加,没有就数组为空
    var apartmentImageAddressInit=[]
    $(function() {
        //得到上传的图片地址
        $.ajax({
            url:"/system/apartment/selectApartmentImg?apartmentId="+$('input[name="id"]').val(),
            type:"post",
            success:function (res){
                apartmentImageAddress=res;
                console.log("res"+res);
                //已经删除了
                if (apartmentImageAddress=="deleted"){
                    apartmentImageAddressInit=[];
                }else{
                    //存在数据
                    apartmentImageAddressInit[0]="<img src='"+apartmentImageAddress+"' class='file-preview-image' alt='Desert' title='Desert'>";
                }
                console.log(apartmentImageAddress)
                fullPath = apartmentImageAddress;
                apartmentImageAddressOnlyNameAndSuffix = '';
                fullPath = fullPath.replaceAll('/', '\\');
                console.log(fullPath);
                pos = fullPath.lastIndexOf('\\');
                apartmentImageAddressOnlyNameAndSuffix = fullPath.substr(pos+1);
                console.log(apartmentImageAddressOnlyNameAndSuffix);
                imageUploder();
            }

        })
        //点击上传事件
        $('#save').click(function(){
            if($("#attach").val() != ""){
                $("#attach").fileinput("upload");
                showLoading();
            }
        });





    })
    function imageUploder(){
        //上传功能
        $('#attach').fileinput({
            maxFileCount:1,
            language: 'zh', //设置语言
            dropZoneTitle: '支持图片批量上传，最多1000M限制',//文字提醒
            uploadUrl:'/apartmentTestUpload',//上传地址
            showRemove:false,
            showUpload:false,  // showRemove, showUpload都为false时，不会显示拖拽框
            enctype: 'multipart/form-data',
            //maxFileCount: 10,//设置文件上传数量
            maxFileSize: 1000 * 1024, //1000MB 文件上传限制大小
            uploadAsync: false,//同步上传  后台参数为MultipartFile[]，若异步参数为MultipartFile
            showCaption: true,
            showPreview: true,
            showCancel:false,
            initialPreview: apartmentImageAddressInit,
            initialPreviewConfig:[
                {
                    width:'120px' ,
                    url:'/deleteApartmentHeadImage' ,//服务器删除操作
                    extra:{fileName:apartmentImageAddressOnlyNameAndSuffix,uploadId:[[${apartment.id}]]}
                }
            ],

            autoReplace:true,//是否自动替换当前图片，默认为false
            showUpload:false,//显示上传按钮
            allowedFileExtensions: [ 'jpg','png','webp','mp4'], //接收的文件后缀
            uploadExtraData: function(){
                return {uploadId : $('input[name="id"]').val()};//文件上传附带的参数
            }
        }).on("fileuploaded", function (event, data, previewId, index){//上传成功后
            //fileinput设置为异步时该回调函数生效



        }).on("filebatchselected", function(event, files) {//选择文件后处理事件
            $('.kv-file-upload').css("display","none");
            if(files.length == 0){
                alert("导入文件格式错误，只能选择pdf文件，请重新选择");
            }
        }).on("filebatchuploadsuccess", function(event, data, previewId, index) {
            //fileinput设置为同步时该回调函数生效
            hideLoading();
            if(data.response.result == 'error'){
                ToastUtils.error(data.response.msg);
            }else {
                alert(data.response.msg);
                $("#attachUploadForm .kv-file-remove").click();//上传完清空附件
                //全部上传完成后延迟0.5秒导出目标excel文件
                setTimeout(function () {
                    var url = ctxPath + '/attach/export';
                    var values = new Array();
                    values.push($('input[name="uploadSn"]').val());
                    openWindowWithPost(url, '导出', [ 'uploadSn' ], values);
                }, 500);
            }
        });



    }
    // 从路径得到资源的名字和后缀
    String.prototype.replaceAll = function(s1, s2) {
        return this.replace(new RegExp(s1, "gm"), s2);
    }


</script>
</body>
</html>